package br.edu.utfpr.backuptools.BackupTools.model.util.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.apache.log4j.Logger;

/**
 * 
 * @author Luan Malaguti Reffatti;
 * 
 */
public class HibernateUtil
{
	private final Logger logger = Logger.getLogger(HibernateUtil.class);
	private final SessionFactory factory;
	
	private static HibernateUtil instance;
	
	private HibernateUtil()
	{
		factory = new HibernateConfiguration().getConfiguration().configure().buildSessionFactory();
		logger.info("Hibernate iniciado");
	}
	
	public HibernateUtil providesHibernateUtil()
	{
		return getInstance();
	}
	
	public static final HibernateUtil getInstance()
	{
		if(instance == null)
		{
			instance = new HibernateUtil();
		}
		return instance;
	}
	
	/**
	 * Pode gerar {@linkplain NullPointerException} caso não tenha nenhuma sessão aberta. Para evitar esse problema usar um
	 * HibernateUtil.currentSession()
	 */
	public void closeCurrentSession() throws NullPointerException
	{
		currentSession().close();
	}
	
	public Session getSession()
	{
		return currentSession();
	}
	
	public Session currentSession()
	{
		return factory.getCurrentSession();
	}
	
	public void beginTransaction()
	{
		currentSession().beginTransaction();
	}
	
	public void commitTransaction() throws HibernateException
	{
		if(currentSession().getTransaction().isActive())
		{
			currentSession().getTransaction().commit();
		}
	}
	
	public void rollbackTransaction() throws HibernateException
	{
		if(currentSession().getTransaction().isActive())
		{
			currentSession().getTransaction().rollback();
		}
	}
	
}
